package com.example.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author: keke
 * @date: 2024/8/8
 */
@Configuration
@ConfigurationProperties(prefix = "spring.datasource1.druid")
@MapperScan(basePackages = {"com.example.daoo"}, sqlSessionTemplateRef = "sqlSessionTemplateTest1")
public class DataSourceConfig1 {

	private String url;
	private String password;

	private String userName;

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	@Bean(name = "dataSourceTest1")
	public DataSource getDateSource1() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
		dataSource.setUrl(getUrl());
		dataSource.setUsername(getPassword());
		dataSource.setPassword(getPassword());
		try {
			dataSource.init();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return dataSource;
	}

	@Bean(name = "sqlSessionFactoryTest1")
	public SqlSessionFactory test1SqlSessionFactory(@Qualifier("dataSourceTest1") DataSource datasource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(datasource);
		return bean.getObject();
	}

	@Bean("sqlSessionTemplateTest1")
	public SqlSessionTemplate test1SqlSessionTemplate(@Qualifier("sqlSessionFactoryTest1") SqlSessionFactory sessionFactory) {
		return new SqlSessionTemplate(sessionFactory);
	}

}
